package com.dzxcqmxm.Dao;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author Payboi
 * @create 2022/6/2-14:17
 * @FileName Dao
 * @Description
 */
public interface Dao {
    //查找并返回数据源对象
    public static DataSource getDataSource(){

        DataSource dataSource = null;

        try {
            Context context = new InitialContext();
            dataSource = (DataSource) context.lookup("java:comp/env/jdbc/dzxcDS");
        } catch (NamingException e) {
            e.printStackTrace();
            System.out.println("NamingException异常："+e);
        }
        return dataSource;
    }

    //返回连接对象的方法
    public default Connection getConnection()throws Exception{
        DataSource dataSource = getDataSource();
        Connection conn = null;

        try {
            conn = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("SQLException异常："+e);
        }
        return conn;
    }
    /**
     * 关闭三个流，
     * 一定要记得用完数据库就关闭，不然会超级卡！！！！
     */
    public static void close(ResultSet rs, PreparedStatement pstm, Connection con){
        if(rs !=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(pstm !=null){
            try {
                pstm.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(con !=null){
            try {
                con.close();//归还连接
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}